package com.dl.dlcommon.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 在自定义的普通类中获取工厂创建的对象
 * @author DL
 * @create 2021-05-30 10:24
 */
@Component
public class ApplicationContextUtil implements ApplicationContextAware {

    private static ApplicationContext context;

    //参数就是已经创建好的工厂对象
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    //根据bean名字获取工厂中指定bean对象
    public static Object getBean(String beanName){
        return context.getBean(beanName);
    }

    //根据bean类型获取工厂中指定对象
    public static Object getBean(Class<Object> clazz){
        return context.getBean(clazz);
    }

    //根据bean类型和name获取工厂中指定对象
    public static <T> T getBean(String beanName, Class<T> clazz){
        return context.getBean(beanName, clazz);
    }

}
